<template>
  <a-modal
    :visible="visible"
    centered
    title="成绩录入"
    okText='提交'
    cancelText="关闭"
    :confirmLoading="confirmLoading"
    :width="1000"
    @cancel="() => { $emit('cancel') }"
    @ok="submitCheck"
    :maskClosable="false"
    >
    <template slot="footer">
      <a-button v-if="isSubRoute" type="primary" @click="showUnqualified" style="margin:0 15px">{{ showUnqualifiedBool? '显示全部' : '显示不合格' }}</a-button>
      <a-button @click="() => { $emit('cancel') }">关闭</a-button>
      <a-button v-if="isSubRoute" type="primary" :disabled="isEdit" @click="submitCheck(false)">保存</a-button>
      <a-button type="primary" :disabled="isEdit" @click="submitCheck(true)">提交</a-button>
    </template>
    <template v-if="isSubRoute">
      <p v-if="params.cjlx == '01'">
        成绩分布情况：
        90分以上：{{cjksxsmdList.length?parseInt(countA/cjksxsmdList.length*100):'0'}}%（{{countA}}/{{cjksxsmdList.length}}）
        [80,90)分：{{cjksxsmdList.length?parseInt(countB/cjksxsmdList.length*100):'0'}}%（{{countB}}/{{cjksxsmdList.length}}）          
        [70-80)分：{{cjksxsmdList.length?parseInt(countC/cjksxsmdList.length*100):'0'}}%（{{countC}}/{{cjksxsmdList.length}}）          
        [60-70)分：{{cjksxsmdList.length?parseInt(countD/cjksxsmdList.length*100):'0'}}%（{{countD}}/{{cjksxsmdList.length}}）         
        60分以下：{{cjksxsmdList.length?parseInt(countE/cjksxsmdList.length*100):'0'}}%（{{countE}}/{{cjksxsmdList.length}}）
      </p>
      <p v-else>
        成绩分布情况：
        A：{{parseInt(countA/cjksxsmdList.length*100)}}%（{{countA}}/{{cjksxsmdList.length}}）          
        B：{{parseInt(countB/cjksxsmdList.length*100)}}%（{{countB}}/{{cjksxsmdList.length}}）          
        C：{{parseInt(countC/cjksxsmdList.length*100)}}%（{{countC}}/{{cjksxsmdList.length}}）          
        D：{{parseInt(countD/cjksxsmdList.length*100)}}%（{{countD}}/{{cjksxsmdList.length}}）      
        E：{{parseInt(countE/cjksxsmdList.length*100)}}%（{{countE}}/{{cjksxsmdList.length}}）     
      </p>
    </template>
    
    <a-table
      rowKey="index"
      :columns="columns"
      :dataSource="showUnqualifiedBool ? UnqualifiedList : cjksxsmdList"
      :pagination="false"
      :scroll="{ y: 300 }">
      <span slot="serial" slot-scope="text, record, index">
        {{ index + 1 }}
      </span>
      <template slot="xsxh" slot-scope="xs, record,index">
        <div :key="index">
          <!-- <a-input style="width: 200px" enter-button v-model="record.xh" @change="onChange(record)"/> -->
          <a-select style="width: 100%" placeholder="" v-model="record.xh" show-search @search="onSearch" @change="onChange(record)">
            <a-spin v-if="kcLoading" slot="notFoundContent" size="small"/>
            <a-select-option v-for="(item,index) in xsxx" :key="index" :value="item.xh">
              {{item.xh}}
            </a-select-option>
          </a-select>
        </div>
      </template>
      <template slot="xsxm" slot-scope="xs, record,index">
        <div :key="index">
          <a-input style="width: 200px" v-model="record.xm"/>
        </div>
      </template>
      <template slot="xsyx" slot-scope="xs, record,index">
        <div :key="index">
          <a-input style="width: 200px" v-model="record.yx"/>
        </div>
      </template>
      <template slot="kscj" slot-scope="xs, record">
        <a-input-number :min="0" :max="100" :disabled="(record.cjztm == '02' || record.cjztm == '03' || record.cjztm == '05' || record.cjztm == '07')?true:(isEdit || !!record.note)" v-if="params.cjlx == '01'" v-model="record.kscj" :defaultValue="0"/>
        <a-select :disabled="(record.cjztm == '02' || record.cjztm == '03' || record.cjztm == '05' || record.cjztm == '07')?true:(isEdit || !!record.note)" :getPopupContainer="trigger => trigger.parentNode" style="min-width: 100px" v-else-if="params.cjlx == '02'" v-model="record.kscj">
          <a-select-option value="A">A</a-select-option>
          <a-select-option value="B">B</a-select-option>
          <a-select-option value="C">C</a-select-option>
          <a-select-option value="D">D</a-select-option>
        </a-select>
        <a-input disabled defaultValue="免修" v-else v-model="record.kscj" />
      </template>
      <template slot="note"  slot-scope="xs, record">
        <a-select :disabled="isEdit || record.kscj || record.kscj === 0" :getPopupContainer="trigger => trigger.parentNode" style="min-width: 100px" v-model="record.note" allowClear @change="$forceUpdate()">
        <!-- <a-select :getPopupContainer="trigger => trigger.parentNode" style="min-width: 100px" allowClear v-model="record.note"> -->
          <a-select-option v-for="i in TYPE0519" :key="i.id" :value="i.name">{{ i.name }}</a-select-option>
        </a-select>
      </template>
      <a slot="action" slot-scope="xs, record, index" @click="deleteStu(index)">删除</a>
    </a-table>
    <a-button v-if="!isSubRoute" style="width: 100%; margin-top: 16px; margin-bottom: 8px" type="dashed" icon="plus" @click="newRow">新增行</a-button>
  </a-modal>
</template>

<script>

export default {
  props: ['visible', 'TYPE0519','modelForm'],
  data () {
    return {
      kcLoading:false,
      xsxx:[],
      params: {},
      cjksxsmdList: [],
      confirmLoading: false,
      sortedInfo: null,
      showUnqualifiedBool:false,
      UnqualifiedList:[],
      countA:0,
      countB:0,
      countC:0,
      countD:0,
      countE:0,
      isEdit:false,
      id:""
    }
  },
  watch:{
    visible(){
      if(this.visible){
        this.UnqualifiedList = []
        this.showUnqualifiedBool = false
        if(!this.visible){
          this.isEdit = false
          this.id = ""
        }
        this.kscjChange()
        this.onSearch()
      }
    }

  },
  computed: {
    isSubRoute () {
      return this.$route.name === '单科成绩录入'
    },
    columns () {
      
      let { sortedInfo } = this
      sortedInfo = sortedInfo || {}
      if (this.$route.name === '单科成绩录入') {
        return [
          {
            title: '序号',
            width:80,
            scopedSlots: { customRender: 'serial' }
          },
          {
            title: '学号',
            width: '170px',
            dataIndex: 'xh'
          },
          {
            title: '姓名',
            width: '80px',
            dataIndex: 'xm'
          },
          {
            title: '所属院系',
            width: '150px',
            dataIndex: 'ssyxmc'
          },
          {
            title: '所属专业',
            width: '150px',
            dataIndex: 'sszymc'
          },
          {
            title: '成绩',
            width: '100px',
            sorter: (a, b) => a.kscj - b.kscj,
            sortOrder: sortedInfo.columnKey === 'kscj' && sortedInfo.order,
            scopedSlots: { customRender: 'kscj' }
          },
          {
            title: '备注',
            width: '70px',
            scopedSlots: { customRender: 'note' }
          }
        ]
      } else {
        return [
          {
            title: '序号',
            scopedSlots: { customRender: 'serial' }
          },
          {
            title: '学号',
            width: '200px',
            scopedSlots: { customRender: 'xsxh' }
          },
          {
            title: '姓名',
            width: '200px',
            scopedSlots: { customRender: 'xsxm' }
          },
          {
            title: '院系',
            width: '200px',
            scopedSlots: { customRender: 'xsyx' }
          },
          {
            title: '成绩',
            width: '150px',
            sorter: (a, b) => a.kscj - b.kscj,
            sortOrder: sortedInfo.columnKey === 'kscj' && sortedInfo.order,
            scopedSlots: { customRender: 'kscj' }
          },
          {
            title: '操作',
            width: '70px',
            scopedSlots: { customRender: 'action' }
          }
        ]
      }
    }
  },
  methods: {
    kscjChange(){
      this.countA = 0
      this.countB = 0
      this.countC = 0
      this.countD = 0
      this.countE = 0

      if(this.params.cjlx != '02'){
        this.cjksxsmdList.map(item=>{
          if(item.kscj >= 90){
            this.countA ++ 
          }else if(90 > item.kscj && item.kscj >= 80){
            this.countB ++
          }else if(80 > item.kscj && item.kscj >= 70){
            this.countC ++
          }else if(70 > item.kscj && item.kscj >= 60){
            this.countD ++
          }else{
            this.countE ++
          }
        })
      }else{
        this.cjksxsmdList.map(item=>{
          if(item.kscj == 'A'){
            this.countA ++ 
          }else if(item.kscj == 'B'){
            this.countB ++
          }else if(item.kscj == 'C'){
            this.countC ++
          }else if(item.kscj == 'D'){
            this.countD ++
          }else{
            this.countE ++
          }
        })
      }
      
    },
    showUnqualified(){
      let params = {
        ...this.modelForm,
        list:this.cjksxsmdList
      }
      console.log(params)
      if(this.showUnqualifiedBool){
        this.UnqualifiedList.map(item=>{
          this.cjksxsmdList.map(i=>{
            if(item.xh == i.xh){
              this.$set(i,'kscj',item.kscj)
              this.$set(i,'note',item.note)

              // i.kscj = item.kscj
              // i.note = item.note
            }
          })
        })
        this.showUnqualifiedBool = !this.showUnqualifiedBool
      }else{
        this.$api.cultivate.bhgcjCheck(params).then(res => {
            this.showUnqualifiedBool = !this.showUnqualifiedBool
            this.UnqualifiedList = res.data
        })
      }
      
      // this.UnqualifiedList = []
      // this.showUnqualifiedBool = !this.showUnqualifiedBool

      // if( this.showUnqualifiedBool && this.params.cjlx != '02'){
      //   this.cjksxsmdList.map(item =>{
      //     if( item.kscj < 60 ){
      //       this.UnqualifiedList.push(item)
      //     }
      //   })
      // }else if(this.showUnqualifiedBool && this.params.cjlx == '02'){
      //   this.cjksxsmdList.map(item =>{
      //     if( item.kscj == 'A' || item.kscj == 'B' ){
      //       this.UnqualifiedList.push(item)
      //     }
      //   })
      // }
      
    },
    newRow () {
      let kscj = ''
      if(this.params.cjlx == '03'){
        kscj = '免修'
      }
      this.cjksxsmdList.push({
        kscj: kscj,
        note: '',
        xh:''
      })
    },
    deleteStu (i) {
      this.cjksxsmdList.splice(i, 1)
    },
    handleChange (pagination, filters, sorter) {
      // 将这三个参数赋值给Vue data，用于后续使用
      this.filteredInfo = filters;
      this.sortedInfo = sorter;
    },
    onSearch(value){
      this.kcLoading = true
      console.log(12121)
       let params = {
        xh: value?value:'',
        kcyx: this.modelForm.kcyx,
        kcdm: this.modelForm.kcdm,
        ksnj: this.modelForm.ksnj,
        ksxn: this.modelForm.ksxn,
        ksxq: this.modelForm.ksxq,
      }
      this.$api.cultivate.scoreSubAddList(params).then((res) => {
       this.xsxx = res.data
       this.kcLoading = false
      })
    },
    onChange(record){
      console.log(record)
      this.xsxx.map((item,index) => {
        if(item.xh == record.xh){
          this.$set(record,'xm',item.xm)
          this.$set(record,'yx',item.ssyxmc)
          if(item.kscj){
            this.$set(record,'kscj',item.kscj)
          }
        }
      })
    },
    submitCheck (bool) {
      // let index = this.cjksxsmdList.findIndex(cj => {
      //   return cj.kscj === undefined || cj.kscj === '' || cj.kscj === null || !cj.xh
      // })

      const hasInvalidRow = this.cjksxsmdList.some(cj => {
        if (!String(cj.kscj) && !cj.note) {
          return true
        } else {
          return false
        }
      })
      if(this.showUnqualifiedBool){
        this.UnqualifiedList.map(item=>{
          this.cjksxsmdList.map(i=>{
            if(item.xh == i.xh){
              i.kscj = item.kscj
              i.note = item.note
            }
          })
        })
      }
      if (!hasInvalidRow || this.params.cjlx === '03') { // 03是免修，不需要成绩
        this.confirmLoading = true
        let params = Object.assign({}, this.params, {
          cjksxsmdList: this.cjksxsmdList.map(s => {
            return {...s, xsxh: s.xh, cjlxm: this.params.cjlx}
          })
        })
        if(this.id) params.id = this.id
        params.sftj = bool
        console.log(params)
        // let apiFn = this.isSubRoute ? 'scoreSubAdd' : 'scoreStuAdd'
        let apiFn = this.isSubRoute ? '/foster/kccj/dkcjlrAdd' : '/foster/kccj/drcjlrAdd'
        this.$postToDow(apiFn,params).then( res => {
          this.$message.success(bool? '提交成功' : '保存成功')
          this.$emit('cancel')
          this.$emit('refresh')
        }).finally(() => {
          this.confirmLoading = false
        })
        // this.$api.cultivate[apiFn](params).then(res => {
        //   this.$message.success(bool? '提交成功' : '保存成功')
        //   this.$emit('cancel')
        //   this.$emit('refresh')
        // }).finally(() => {
        //   this.confirmLoading = false
        // })
      } else {
        this.$message.warn('请输入完整的成绩，成绩为空时备注必填')
      }
    }
  }
}
</script>

<style scoped lang="less">
</style>
